<?php
namespace Gwit\PlateformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

use Gwit\PlateformBundle\Entity\Monitor;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

/**
 * Description of MonitorController
 *
 * @author root
 */
class MonitorController extends Controller {

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = new Monitor();
            $entity->setName("toto");
            $entity->setPosition(12);
            $entity->setFavorite(1);
            $entity->setUserId(1021);
            $em->persist($entity);
            $em->flush();
        return new Response('Hello world!');
    }
    
    /**
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws AccessDeniedException 
     */
    public function getmonitorAction(Request $request){
        
        $user = $this->container->get('security.context')->getToken()->getUser();

        // Et pour vérifier que l'utilisateur est authentifié (et non un anonyme)
        if( ! is_object($user) )
        {
            throw new AccessDeniedException('Vous n\'êtes pas authentifié.');
        }
        
        $em = $this->getDoctrine()->getEntityManager();

        $monitors = $em->getRepository('GwitPlateformBundle:Monitor')->findBy(array('user_id' => $user->getId()), array('dateCreated' => 'ASC'));
        
        $post=array();
        $i = 0;
        foreach($monitors as $monitor){
            $post[$i] = array(
                "name" => $monitor->getName(),
                "position" => $monitor->getPosition(),
                "favoris" => $monitor->getFavorite(),
            );
            $i = 1 + $i;
        }
        
        $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new 
            JsonEncoder()));
        $json = $serializer->serialize($monitors, 'json');

        
        return new Response($json);
    }
    
    /**
     * Fonction de creation et sauvegarde d'un moniteur
     * appelé par une requete AJAX
     * 
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws AccessDeniedException
     */
    public function saveAction(Request $request){
        $em = $this->getDoctrine()->getEntityManager();
        if($request->getMethod() == 'POST') {
            if ($request->isXmlHttpRequest())
            {
                if (0 === strpos($this->getRequest()->headers->get('Content-Type'), 'application/json')) {
                    
                    $user = $this->container->get('security.context')->getToken()->getUser();

                    // Et pour vérifier que l'utilisateur est authentifié (et non un anonyme)
                    if( ! is_object($user) )
                    {
                        throw new AccessDeniedException('Vous n\'êtes pas authentifié.');
                    }
                    
                    try{
                        //Get POST data
                        $data = json_decode($this->getRequest()->getContent(), true);
                        $this->getRequest()->request->replace(is_array($data) ? $data : array());
                        $tmp = $em->getRepository('GwitPlateformBundle:Monitor')->findBy(array('name' => $data["monitor"], 'user_id' => $user->getId()));
                        if($tmp != null ){
                            throw new \Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException("");
                        }
                        
                        //Creation de l'entité moniteur
                        $entity = new Monitor();
                        $entity->setName($data["monitor"]);
                        $entity->setComment($data["comment"]);
                        $entity->setUserId($user->getId());
                        
                        //TODO: Modifier la base de donnée pour avoir position relatif sur ecran
                        $entity->setPosition(1);
                        $entity->setFavorite(0);
                        
                        //Save into database
                        $em->persist($entity);
                        $em->flush();
                        
                        $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new 
                            JsonEncoder()));
                        $json = $serializer->serialize($entity, 'json');

                        return new Response($json);
                    }catch(Exception $e){
                        return new Response($e);
                    }
                }
            }
        }
        return new Response("End");
    }
    
    /**
     * Delete monitor
     * @param type $id
     * @return type
     * @throws type 
     */
    public function deleteAction(Request $request)
    {
        $em = $this->getDoctrine()->getEntityManager();
        
        if($request->getMethod() == 'POST') {
            if ($request->isXmlHttpRequest())
            {
                if (0 === strpos($this->getRequest()->headers->get('Content-Type'), 'application/json')) {
                    
                    $user = $this->container->get('security.context')->getToken()->getUser();

                    // Et pour vérifier que l'utilisateur est authentifié (et non un anonyme)
                    if( ! is_object($user) )
                    {
                        throw new AccessDeniedException('Vous n\'êtes pas authentifié.');
                    }
                    
                    try{
                        //Get POST data
                        $data = json_decode($this->getRequest()->getContent(), true);
                        $this->getRequest()->request->replace(is_array($data) ? $data : array());
                        
                        //Select monitor
                        $entity = $em->getRepository('GwitPlateformBundle:Monitor')->findBy(
                                array('id' => $data["monitor"], 'user_id' => $user->getId()));
                        
                        if (!$entity) {
                            throw $this->createNotFoundException('Unable to find monitor.');
                        }
                        
                        //delete into database
                        $em->remove($entity[0]);
                        $em->flush();
                        
                        return new Response("Moniteur détruit !");
                    }catch(Exception $e){
                        return new Response($e);
                    }
                }
            }
        }
        
        return new Response("End");
    }
    
    /**
     * Controlleur de mise à jour d'un moniteur
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws AccessDeniedException
     * @throws type 
     */
    public function updateAction(Request $request){
        $em = $this->getDoctrine()->getEntityManager();
        
        if($request->getMethod() == 'POST') {
            if ($request->isXmlHttpRequest())
            {
                if (0 === strpos($this->getRequest()->headers->get('Content-Type'), 'application/json')) {
                    
                    $user = $this->container->get('security.context')->getToken()->getUser();

                    // Et pour vérifier que l'utilisateur est authentifié (et non un anonyme)
                    if( ! is_object($user) )
                    {
                        throw new AccessDeniedException('Vous n\'êtes pas authentifié.');
                    }
                    
                    try{
                        //Get POST data
                        $data = json_decode($this->getRequest()->getContent(), true);
                        $this->getRequest()->request->replace(is_array($data) ? $data : array());
                        
                        //Select monitor
                        $entity = $em->getRepository('GwitPlateformBundle:Monitor')->findBy(
                                array('id' => $data["monitor"], 'user_id' => $user->getId()));
                        
                        if (!$entity) {
                            throw $this->createNotFoundException('Unable to find monitor.');
                        }
                        
                        //
                        $entity[0]->setName($data["newname"]);
                        $entity[0]->setComment($data["newcomment"]);
                        
                        //delete into database
                        $em->persist($entity[0]); 
                        $em->flush();
                        
                        return new Response("Moniteur détruit !");
                    }catch(Exception $e){
                        return new Response($e);
                    }
                }
            }
        }
        
        return new Response("End");
    }
    
    public function newtopAction(Request $request){
        $em = $this->getDoctrine()->getEntityManager();
        
        if($request->getMethod() == 'POST') {
            if ($request->isXmlHttpRequest())
            {
                if (0 === strpos($this->getRequest()->headers->get('Content-Type'), 'application/json')) {
                    
                    $user = $this->container->get('security.context')->getToken()->getUser();

                    // Et pour vérifier que l'utilisateur est authentifié (et non un anonyme)
                    if( ! is_object($user) )
                    {
                        throw new AccessDeniedException('Vous n\'êtes pas authentifié.');
                    }
                    
                    try{
                        //Get POST data
                        $data = json_decode($this->getRequest()->getContent(), true);
                        $this->getRequest()->request->replace(is_array($data) ? $data : array());
                        
                        //Select monitor
                        $monitors = $em->getRepository('GwitPlateformBundle:Monitor')->findBy(array('user_id' => $user->getId()), array('dateCreated' => 'ASC'));
                        if (!$monitors) {
                            throw $this->createNotFoundException('Unable to find monitor.');
                        }
                        
                        foreach($monitors as $monitor){
                            if ($monitor->getOntop()){
                                if($monitor->getId() == $data["monitor"]){
                                    break;
                                }else{
                                    $monitor->setOntop(false);
                                    $em->persist($monitor);
                                }
                            }else{
                                if($monitor->getId() == $data["monitor"]){
                                    $monitor->setOntop(true);
                                    $em->persist($monitor);
                                }
                            }
                        }
                        
                        $em->flush();
                        
                        return new Response("Position changé !");
                    }catch(Exception $e){
                        return new Response($e);
                    }
                }
            }
        }
        
        return new Response("End");
    }
    
    /**
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws AccessDeniedException 
     */
    public function testAction(Request $request){
        
        $user = $this->container->get('security.context')->getToken()->getUser();

        // Et pour vérifier que l'utilisateur est authentifié (et non un anonyme)
        if( ! is_object($user) )
        {
            throw new AccessDeniedException('Vous n\'êtes pas authentifié.');
        }
        
        $em = $this->getDoctrine()->getEntityManager();

        $monitors = $em->getRepository('GwitPlateformBundle:Monitor')->findBy(array('user_id' => $user->getId()), array('dateCreated' => 'ASC'));
        
        $post=array();
        $i = 0;
        foreach($monitors as $monitor){
            $post[$i] = array(
                "name" => $monitor->getName(),
                "position" => $monitor->getPosition(),
                "favoris" => $monitor->getFavorite(),
            ); 
            $i = 1 + $i;
        }
        
        $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new 
            JsonEncoder()));
        $json = $serializer->serialize($monitors, 'json');

        
        return new Response($json);
    }
}
